<template>
  <div>
    <n-card>
      <n-space style="margin-bottom: 10px">
        <n-input v-model:value="queryForm.programmeSettingName" placeholder="请输入方案名称" style="width: 300px">
        </n-input>
        <n-button type="primary" @click="getList">
          <template #icon>
            <n-icon>
              <Search/>
            </n-icon>
          </template>
          查询
        </n-button>
      </n-space>
    </n-card>
    <n-card style="margin-top: 5px">
      <n-space justify="space-between">
        <n-button type="primary" style="margin-bottom: 10px;"
                  @click="resetProgrammeForm() ;formTitle = '新增方案'; addModalShow = true">
          <template #icon>
            <n-icon>
              <AddSharp/>
            </n-icon>
          </template>
          新增
        </n-button>
        <n-button type="info" @click="syncOnlineProgrammeSetting">
          同步云端预设
        </n-button>
      </n-space>
      <n-scrollbar
          :content-style="{padding: '5px 5px 5px 5px', height: clientHeight - (layoutHeaderHeight  + tabsHeight + 225) + 'px'}">
        <n-grid x-gap="4" y-gap="10" :cols="5" item-responsive responsive="screen">
          <n-gi v-for="programme in programmeList">
            <n-card :title="programme.programmeName" :header-style="{padding: '5px 5px 0px 5px'}"
                    :content-style="{padding: '5px 5px 5px 5px'}">
              <template #header-extra>
                {{ programme?.engineType }}
              </template>
              <template #cover>
                <n-space justify="center">
                  <n-image height="300" style="max-height:  300px" :object-fit="'cover'"
                           v-if="programme.imageUrl"
                           :src="fileFunction.getProgrammeSettingCoverImage(programme?.imageUrl)">
                  </n-image>
                </n-space>
              </template>
              <n-space justify="space-between" style="margin-top: 5px;">
                <n-tag type="primary">
                  <n-ellipsis style="width: 130px">
                    {{ programme?.programmeTags }}
                  </n-ellipsis>
                </n-tag>
                <n-tag v-if="programme.isOnline" type="error">
                  云端资源
                </n-tag>
              </n-space>
              <template #action>
                <n-space justify="space-between">
                  <n-button size="small" type="primary" @click="openMarkdown(programme)">文档</n-button>
                  <n-dropdown
                      placement="bottom-start"
                      trigger="click"
                      size="medium"
                      :options="buttonOptions"
                      @select="(key:string,option:DropdownOption)=>{buttonSelect(key,option,programme)}"
                  >
                    <n-button size="small" type="info">其他功能</n-button>
                  </n-dropdown>
                </n-space>
              </template>
            </n-card>
          </n-gi>
        </n-grid>
      </n-scrollbar>
      <n-space justify="end" style="margin-top: 10px">
        <n-pagination
            :display-order="['quick-jumper', 'pages', 'size-picker']"
            :item-count="tableTotal"
            :page-size="paginationReactive.pageSize"
            :page-sizes="paginationReactive.pageSizes"
            show-quick-jumper
            show-size-picker
            :on-update:page-size="onPageSizeChange"
            :on-update:page="onPageChange"
        />
      </n-space>
    </n-card>

    <n-drawer v-model:show="addModalShow" :width="800" :on-after-leave="getList">
      <n-drawer-content :title="formTitle">

        <n-form ref="formRef" :model="programmeForm" :rules="rules">
          <n-form-item
              label="方案名称"
              path="programmeName"
          >
            <n-input v-model:value="programmeForm.programmeName" clearable/>
          </n-form-item>
          <n-form-item
              label="方案类型"
              path="programmeType"
          >
            <n-select
                :options="programmeTypeOption"
                v-model:value="programmeForm.programmeType"
                clearable
            >
            </n-select>
          </n-form-item>
          <n-form-item
              label="绘画引擎"
              path="engineType">
            <n-select
                :options="paintEngineTypeOptions"
                v-model:value=programmeForm.engineType>
            </n-select>
          </n-form-item>

          <n-form-item :span="24" label=" " path="characterAvatar">
            <n-card title="封面图">
              <template #header-extra>
                <n-space justify="end" v-if="programmeForm.imageUrl">
                  <n-button size="small" type="warning" @click="programmeForm.imageUrl = ''">清除</n-button>
                </n-space>
              </template>
              <n-space justify="center">
                <n-image
                    :style="{
                        width: canvasWidth + 'px',
                        height: canvasHeight + 'px'
                        }"
                    v-if="programmeForm.imageUrl && programmeForm.imageUrl.startsWith('data:image')"
                    :src="programmeForm.imageUrl"
                    alt=""
                    @load="handleImgLoad"/>
                <n-image
                    :style="{
                        width: canvasWidth + 'px',
                        height: canvasHeight + 'px'
                      }"
                    v-if="programmeForm.imageUrl && !programmeForm.imageUrl.startsWith('data:image')"
                    :src="fileFunction.getProgrammeSettingCoverImage(programmeForm.imageUrl)"
                    alt=""
                    @load="handleImgLoad"/>
              </n-space>
              <n-empty description="未上传图片" v-if="!programmeForm.imageUrl">
                <template #extra>
                  <n-upload
                      :custom-request="customRequest"
                      :accept="'image/*'"
                  >
                    <n-button>上传图片</n-button>
                  </n-upload>
                </template>
              </n-empty>
            </n-card>
          </n-form-item>

          <n-form-item
              label="图片地址">
            <n-input
                v-model:value="programmeForm.imageUrl"
                clearable>
            </n-input>
          </n-form-item>
          <n-form-item
              label="方案标签"
              path="programmeTags"
          >
            <n-dynamic-tags v-model:value="programmeForm.tags"/>
          </n-form-item>
          <n-form-item
              label="方案描述"
              path="programmeDescription"
          >
            <n-input type="textarea" v-model:value="programmeForm.programmeDescription" show-count :maxlength="200"
                     clearable/>
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button @click="addModalShow=false">取消</n-button>
            <n-button type="primary" @click="addProgramme" :loading="addLoading">提交</n-button>
          </n-space>
        </template>
      </n-drawer-content>
    </n-drawer>

    <n-modal
        v-model:show="markdownShow"
        preset="card"
        class="custom-card"
        :bordered="false"
        style=" width:1400px"
        title="方案说明编写"
        :mask-closable="false"
        :close-on-esc="false"
    >
      <MdEditor v-model="selectedProgramme.programmeMarkdown" style="height: 700px;" :theme="darkTheme?'dark':'light'"/>
      <template #footer>
        <n-space justify="end">
          <n-button @click="markdownShow = false">取消</n-button>
          <n-button type="primary" @click="addProgrammeWithNoValidate" :loading="addLoading">提交</n-button>
        </n-space>
      </template>
    </n-modal>

    <n-drawer v-model:show="initShow" :width="drawerWidth">
      <n-drawer-content closable :title="`方案配置        绘图引擎:`+ selectedProgramme.engineType">
        <template #footer>
          <n-space justify="end">
            <n-button type="primary" @click="saveConfig">
              保存配置
            </n-button>
          </n-space>
        </template>
        <Setting ref="settingRef" :programme="selectedProgramme"></Setting>
      </n-drawer-content>
    </n-drawer>

  <n-modal  v-model:show="syncModalShow" @after-leave="getList" >
    <n-card
      style="width: 600px"
      title="同步进度"
      :bordered="false"
      size="huge"
      role="dialog"
      aria-modal="true"
    >
    <SyncDataSchdule v-if="syncTaskId" :taskId="syncTaskId"></SyncDataSchdule>
    </n-card>
  </n-modal>


  </div>

</template>

<script lang="ts" setup>
import {h, nextTick, onMounted, reactive, ref} from 'vue'
import {DropdownOption, NButton, NTag, UploadCustomRequestOptions} from "naive-ui";
//@ts-ignore
import Bus from '@/components/file/box/GlobalUploader/utils/bus.js'
//@ts-ignore
import fileFunction from '@/libs/globalFunction/file.js'
import {AddSharp, Search, SyncCircleOutline, CheckmarkSharp} from "@vicons/ionicons5"
import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import Setting from "@/views/pages/programme/components/setting.vue";

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";
import {programmeSettingController} from "@/api/story/programmeSetting.api";
import {resourceController} from "@/api/resource/resourceController.api";
import {creatorDict} from "@/dictionary/creatorDict";
import {setting} from "@/config/setting";
import SyncDataSchdule from "@/components/syncData/syncDataSchdule.vue";


const {paintEngineTypeOptions} = creatorDict()
const {client} = setting
const settingRef = ref(null)
// 设置canvas宽高
const canvasWidth = ref(300)
const canvasHeight = ref(300)
const tableTotal = ref(0)
const syncTaskId = ref(null)
const syncModalShow = ref(false)
const programmeTypeOption = ref([
  {
    label: '视频转绘',
    value: 'VIDEO'
  },
  {
    label: '小说转绘',
    value: 'NOVEL'
  }
])


const buttonOptions = [
  {
    label: '配置方案',
    key: 'programme'
  },
  {
    label: '编辑方案',
    key: 'edit'
  },
  {
    label: '删除方案',
    key: 'delete'
  }, {
    label: '上传',
    key: 'upload'
  }]

const programmeList = ref<Array<any>>([])
const queryForm = ref({
  programmeSettingName:'',
  engineType : ''
})
const tableLoading = ref(false)
const addLoading = ref(false)
const addModalShow = ref(false)
const markdownShow = ref(false)
const initShow = ref(false)
const resourceOption = ref([])
const selectedResource = ref("")
const selectedResourceOption = ref({
  label: '',
  value: '',
  type: ''
})
const SdImg2ImgRef = ref(null)
const drawerWidth = ref(1400)

const programmeForm = reactive({
  id: '',
  programmeName: '',
  programmeType: 'VIDEO',
  programmeDescription: '',
  programmeTags: '',
  programmeMarkdown: '',
  tags: [],
  imageUrl: '',
  engineType: ''
})

const resetProgrammeForm = () => {
  programmeForm.id = ''
  programmeForm.programmeName = ''
  programmeForm.programmeType = 'VIDEO'
  programmeForm.programmeDescription = ''
  programmeForm.programmeTags = ''
  programmeForm.programmeMarkdown = ''
  programmeForm.tags = []
  programmeForm.imageUrl = ''
  programmeForm.engineType = ''
}

const paintEngineConfig = ref(null)

const formRef = ref(null)
const formTitle = ref('新增方案')
const selectedProgramme = ref(null)


const rules = {
  programmeName: [
    {required: true, message: '请输入方案名称', trigger: 'blur'},
  ],
  programmeType: [
    {required: true, message: '请选择方案类型', trigger: 'change'}
  ],
  engineType: [
    {required: true, message: '请选择绘画引擎', trigger: 'change'}
  ]
}

const getList = () => {
  tableLoading.value = true
  programmeSettingController.getProgrammeSettingList({
    programmeSettingName: queryForm.value.programmeSettingName,
    engineType: queryForm.value.engineType
  },{
    page: paginationReactive.page,
    pageSize: paginationReactive.pageSize
  }).then((res) => {
    if (res.code === 200) {
      tableTotal.value = res.data.total
      programmeList.value = res.data.records
      programmeList.value.forEach((item) => {
        item.paintEngineConfig = initPaintEngineConfig(item.programmeConfig, item.engineType)
      })
    }
  }).finally(() => {
    tableLoading.value = false
  })
}

const initPaintEngineConfig = (programmeConfig: string, engineType: string) => {
  if (programmeConfig == null || programmeConfig == '') {
    return initConfig(engineType)
  } else {
    return JSON.parse(programmeConfig)
  }
}


const initConfig = (engineType: string) => {
  if (engineType == 'Fooocus') {
    return {
      resourceId: '',
      prompt: '',
      negative_prompt: '',
      style_selections: [
        "Fooocus V2",
        "Fooocus Enhance",
        "Fooocus Sharp"
      ],
      performance_selection: 'Extreme Speed',
      aspect_ratios_selection: '1152*896',
      image_number: 1,
      image_seed: -1,
      sharpness: 2,
      guidance_scale: 4,
      base_model_name: 'animaPencilXL_v100.safetensors',
      refiner_model_name: '',
      refiner_switch: 0.5,
      loras: [{
        model_name: "sd_xl_offset_example-lora_1.0.safetensors",
        weight: 0.1
      }, {
        model_name: "",
        weight: 1
      }, {
        model_name: "",
        weight: 1
      }, {
        model_name: "",
        weight: 1
      }],
      advanced_params: {
        adaptive_cfg: 7,
        adm_scaler_end: 0.3,
        adm_scaler_negative: 0.8,
        adm_scaler_positive: 1.5,
        canny_high_threshold: 128,
        canny_low_threshold: 64,
        controlnet_softness: 0.25,
        debugging_cn_preprocessor: false,
        debugging_inpaint_preprocessor: false,
        disable_intermediate_results: false,
        disable_preview: false,
        disable_seed_increment: false,
        freeu_b1: 1.01,
        freeu_b2: 1.02,
        freeu_enabled: false,
        freeu_s1: 0.99,
        freeu_s2: 0.95,
        inpaint_disable_initial_latent: false,
        inpaint_engine: "v1",
        inpaint_erode_or_dilate: 0,
        inpaint_mask_upload_checkbox: false,
        inpaint_respective_field: 1,
        inpaint_strength: 1,
        invert_mask_checkbox: false,
        mixing_image_prompt_and_inpaint: false,
        mixing_image_prompt_and_vary_upscale: false,
        overwrite_height: -1,
        overwrite_step: -1,
        overwrite_switch: -1,
        overwrite_upscale_strength: -1,
        overwrite_vary_strength: -1,
        overwrite_width: -1,
        refiner_swap_method: "joint",
        sampler_name: "dpmpp_2m_sde_gpu",
        scheduler_name: "karras",
        skipping_cn_preprocessor: false
      },
      require_base64: true,
      async_process: false,
    }
  } else if (engineType == 'SD') {
    return {
      defaultPrompt: '',
      defaultNegativePrompt: 'multiple breasts, (mutated hands and fingers:1.5 ), (long body :1.3), (mutation, poorly drawn :1.2) , black-white, bad anatomy, liquid body, liquid tongue, disfigured, malformed, mutated, anatomical nonsense, text font ui, error, malformed hands, long neck, blurred, lowers, lowres, bad anatomy, bad proportions, bad shadow, uncoordinated body, unnatural body, fused breasts, bad breasts, huge breasts, poorly drawn breasts, extra breasts, liquid breasts, heavy breasts, missing breasts, huge haunch, huge thighs, huge calf, bad hands, fused hand, missing hand, disappearing arms, disappearing thigh, disappearing calf, disappearing legs, fused ears, bad ears, poorly drawn ears, extra ears, liquid ears, heavy ears, missing ears, fused animal ears, bad animal ears, poorly drawn animal ears, extra animal ears, liquid animal ears, heavy animal ears, missing animal ears, text, ui, error, missing fingers, missing limb, fused fingers, one hand with more than 5 fingers, one hand with less than 5 fingers, one hand with more than 5 digit, one hand with less than 5 digit, extra digit, fewer digits, fused digit, missing digit, bad digit, liquid digit, colorful tongue, black tongue, cropped, watermark, username, blurry, JPEG artifacts, signature, 3D, 3D game, 3D game scene, 3D character, malformed feet, extra feet, bad feet, poorly drawn feet, fused feet, missing feet, extra shoes, bad shoes, fused shoes, more than two shoes, poorly drawn shoes, bad gloves, poorly drawn gloves, fused gloves, bad cum, poorly drawn cum, fused cum, bad hairs, poorly drawn hairs, fused hairs, big muscles, ugly, bad face, fused face, poorly drawn face, cloned face, big face, long face, bad eyes, fused eyes poorly drawn eyes, extra eyes, malformed limbs, more than 2 nipples, missing nipples, different nipples, fused nipples, bad nipples, poorly drawn nipples, black nipples, colorful nipples, gross proportions. short arm, (((missing arms))), missing thighs, missing calf, missing legs, mutation, duplicate, morbid, mutilated, poorly drawn hands, more than 1 left hand, more than 1 right hand, deformed, (blurry), disfigured, missing legs, extra arms, extra thighs, more than 2 thighs, extra calf, fused calf, extra legs, bad knee, extra knee, more than 2 legs, bad tails, bad mouth, fused mouth, poorly drawn mouth, bad tongue, tongue within mouth, too long tongue, black tongue, big mouth, cracked mouth, bad mouth, dirty face, dirty teeth, dirty pantie, fused pantie, poorly drawn pantie, fused cloth, poorly drawn cloth, bad pantie, yellow teeth, thick lips, bad cameltoe, colorful cameltoe, bad asshole, poorly drawn asshole, fused asshole, missing asshole, bad anus, bad pussy, bad crotch, bad crotch seam, fused anus, fused pussy, fused anus, fused crotch, poorly drawn crotch, fused seam, poorly drawn anus, poorly drawn pussy, poorly drawn crotch, poorly drawn crotch seam, bad thigh gap, missing thigh gap, fused thigh gap, liquid thigh gap, poorly drawn thigh gap, poorly drawn anus, bad collarbone, fused collarbone, missing collarbone, liquid collarbone, strong girl, obesity, worst quality, low quality, normal quality, liquid tentacles, bad tentacles, poorly drawn tentacles, split tentacles, fused tentacles, missing clit, bad clit, fused clit, colorful clit, black clit, liquid clit, QR code, bar code, censored, safety panties, safety knickers, beard, furry ,pony, pubic hair, mosaic, excrement, faeces, shit, futa, testis',
      defaultSeed: -1,
      defaultSamplerName: 'Euler a',
      defaultBatchSize: 1,
      defaultSteps: 20,
      defaultWidth: 512,
      defaultHeight: 512,
      promptEn: '',
      defaultCfgScale: 7,
      savePath: '',
      defaultRestoreFaces: false,
      defaultEnableHr: false,
      defaultHrUpscaler: 'R-ESRGAN 4x+',
      defaultHrScale: 2.0,
      defaultDenoisingStrength: 0.5,
      defaultHrSecondPassSteps: 8
    }
  } else if (engineType == 'MJ') {
    return {
      ar: '4:3',
      model: 'MJv6',
      quality: 'high',
      chaos: 0,
      mode: '普通',
      base64: '',
      prompt: '',
      no: '',
      plotMode: '2',
      command: '',
      resourceId: '',
      enableReferencePic: true,
      botType: 'mjbot',
      crefValue: 0,
      srefValue: 0,
      srefImage1Url: '',
      srefImage2Url: '',
      srefImage3Url: ''
    }
  }
}


const addProgramme = () => {
  addLoading.value = true
  formRef.value.validate().then(() => {
    programmeForm.programmeTags = programmeForm.tags.join(',')
    programmeSettingController.addProgrammeSetting(programmeForm).then((res) => {
      if (res.code === 200) {
        window.$message.success(res.msg)
        addModalShow.value = false
        getList()
      }
    }).finally(() => {
      addLoading.value = false
    })
  })
}

const addProgrammeWithNoValidate = () => {
  addLoading.value = true
  programmeSettingController.addProgrammeSetting(selectedProgramme.value).then((res) => {
    if (res.code === 200) {
      window.$message.success(res.msg)
      markdownShow.value = false
      getList()
    }
  }).finally(() => {
    addLoading.value = false
  })
}


const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  pageSizes: [10, 30, 60]
})


const onPageChange = (page: number) => {
  paginationReactive.page = page
  getList()
}
const onPageSizeChange = (pageSize: number) => {
  paginationReactive.pageSize = pageSize
  getList()
}


const columns = [
  {
    title: '#',
    key: 'key',
    width: 50,
    render: (row, index) => {
      return `${index + 1}`
    }
  },
  {
    title: '方案名称',
    key: 'programmeName',
    ellipsis: {
      tooltip: true,
      lineClamp: 1
    }
  },
  {
    title: '来源',
    key: 'isRemote',
    width: 140,
    render: (row: any) => {
      if (row.isRemote == '1') {
        return h(NTag, {type: 'primary'}, {default: () => '系统自带'})
      } else {
        return h(NTag, {type: 'warning'}, {default: () => '自定义'})
      }
    }
  },
  {
    title: '类型',
    key: 'status',
    render: (row) => {
      if (row.programmeType == 'VIDEO') {
        return h(NTag, {type: 'success'}, {default: () => '视频转绘'})
      } else {
        return h(NTag, {type: 'warning'}, {default: () => '小说转绘'})
      }
    }
  },
  {
    title: '绘画引擎',
    key: 'engineType'
  }, {
    title: '标签',
    key: 'site',
    width: 400,
    render: (row: any) => {
      const tagRender = []
      const tags = row.programmeTags?.split(',')
      if (tags == null) {
        return null;
      }
      for (let i = 0; i < tags.length; i++) {
        tagRender.push(h(NTag, {type: 'info', style: 'margin-left:5px;'}, {default: () => tags[i]}))
      }
      return tagRender
    }
  },
  {
    title: '操作',
    key: 'address',
    width: 300,
    render(rowData: any) {
      const buttons = [];

      if (!client) {
        buttons.push(h(
            NButton,
            {
              size: 'small',
              type: 'primary',
              onClick: () => {
                uploadToTuChuang(rowData.id)
              }
            },
            {default: () => '上传图床'}
        ))
      }

      buttons.push(h(
          NButton,
          {
            size: 'small',
            type: 'primary',
            onClick: () => {
              selectedProgramme.value = rowData
              if (selectedProgramme.value.programmeMarkdown == null || selectedProgramme.value.programmeMarkdown == '') {
                selectedProgramme.value.programmeMarkdown = ''
              }
              markdownShow.value = true
            }
          },
          {default: () => '方案说明'}
      ))
      buttons.push(h(
          NButton,
          {
            size: 'small',
            type: 'info',
            style: 'margin-left:5px',
            onClick: () => {
              selectedResource.value = ''
              selectedProgramme.value = rowData
              console.log(selectedProgramme.value)
              initShow.value = true
            }
          },
          {default: () => '配置'}
      ))

      buttons.push(h(
          NButton,
          {
            size: 'small',
            type: 'warning',
            style: 'margin-left:5px',
            onClick: () => {
              if (rowData.isRemote == '1') {
                window.$message.warning('系统自带方案不可编辑')
                return
              }
              formTitle.value = '编辑方案'
              programmeForm.id = rowData.id
              programmeForm.programmeDescription = rowData.programmeDescription
              programmeForm.programmeType = rowData.programmeType
              programmeForm.programmeName = rowData.programmeName
              programmeForm.programmeTags = rowData.programmeTags
              programmeForm.programmeMarkdown = rowData.programmeMarkdown
              programmeForm.imageUrl = rowData.imageUrl
              programmeForm.engineType = rowData.engineType
              programmeForm.tags = rowData.programmeTags.split(',')
              addModalShow.value = true
            }
          },
          {default: () => '编辑'}
      ))

      buttons.push(h(
          NButton,
          {
            size: 'small',
            type: 'error',
            style: 'margin-left:5px',
            onClick: () => {
              if (rowData.isRemote == '1') {
                window.$message.warning('系统自带方案不可删除')
                return
              }
              window.$dialog.error({
                title: "温馨提醒",
                content: "删除操作不可逆，是否继续？",
                positiveText: "确定",
                negativeText: "取消",
                onPositiveClick: () => {
                  programmeSettingController.deleteProgrammeSetting(rowData.id).then((res) => {

                    if (res.code === 200) {
                      window.$message.success(res.msg)
                      getList()
                    }
                  })
                }
              })
            }
          },
          {default: () => '删除'}
      ))
      return buttons
    }
  }
]


const openMarkdown = (rowData: any) => {
  selectedProgramme.value = rowData
  if (selectedProgramme.value.programmeMarkdown == null || selectedProgramme.value.programmeMarkdown == '') {
    selectedProgramme.value.programmeMarkdown = ''
  }
  markdownShow.value = true
}

const getResourceInfo = async () => {
  try {
    const res = await resourceController.getSDResource('SD');
    if (res.code === 200) {
      res.data.forEach((item: any) => {
        // @ts-ignore
        resourceOption.value.push({
          label: item.resourceName,
          value: item.id,
          type: item.type,
        });
      })
    } else {
      window.$message.error(res.msg);
    }
  } catch (error) {
    // 处理错误
    console.error(error);
  }
}

const resourceSelect = (value: string, option: any) => {
  selectedResource.value = value
  selectedResourceOption.value = option;
  loadConfig()
}

const loadConfig = () => {
  if (selectedProgramme.value.programmeConfig == null || selectedProgramme.value.programmeConfig == '') {

  } else {
    paintEngineConfig.value = JSON.parse(selectedProgramme.value.programmeConfig)
  }
}


const saveConfig = async () => {
  const validateOk = await settingRef.value?.validate()
  if (validateOk) {
    selectedProgramme.value.programmeConfig = JSON.stringify(selectedProgramme.value.paintEngineConfig)
    addProgrammeWithNoValidate()
    initShow.value = false
  }
}


const uploadToTuChuang = (programmeSettingId: string) => {
  programmeSettingController.uploadToTuChuang(programmeSettingId).then((res) => {
    if (res.code === 200) {
      window.$message.success(res.msg)
    }
  })
}

onMounted(() => {
  getList()
  getResourceInfo()
})


const customRequest = (uploadOption: UploadCustomRequestOptions) => {
  const reader = new FileReader();
  //@ts-ignore
  reader.readAsDataURL(uploadOption.file.file);
  reader.onloadend = () => {
    let image = new Image()
    image.src = reader.result
    //@ts-ignore
    programmeForm.imageUrl = reader.result
  };
}


const handleImgLoad = (e: any) => {
  const image = e.target;
  let image_new = new Image()
  image_new.src = image.src
  image_new.onload = function () {
    // 计算图片宽高比例
    let imgRatio = image_new.width / image_new.height
    if (image_new.width > 400
        || image_new.height > 400) {
      // 计算缩放后的宽高
      if (imgRatio > 1) {
        canvasWidth.value = 400
        canvasHeight.value = image_new.height / (image_new.width / 400)
      } else {
        // 图片比较宽
        canvasWidth.value = image_new.width / (image_new.height / 400)
        canvasHeight.value = 400
      }
    } else {
      canvasWidth.value = image_new.width
      canvasHeight.value = image_new.height
    }
  }
}

const buttonSelect = (key: string, option: DropdownOption, programme: any) => {
  console.log(programme)
  if (key == 'programme') {
    selectedProgramme.value = programme
    initShow.value = true
  } else if (key == 'edit') {
    if (programme.isOnline == '1') {
      window.$message.warning('系统自带方案不可编辑')
      return
    }
    formTitle.value = '编辑方案'
    programmeForm.id = programme.id
    programmeForm.programmeDescription = programme.programmeDescription
    programmeForm.programmeType = programme.programmeType
    programmeForm.programmeName = programme.programmeName
    programmeForm.programmeTags = programme.programmeTags
    programmeForm.programmeMarkdown = programme.programmeMarkdown
    programmeForm.imageUrl = programme.imageUrl
    programmeForm.engineType = programme.engineType
    programmeForm.tags = programme.programmeTags.split(',')
    addModalShow.value = true
  } else if (key == 'delete') {
    if (programme.isOnline == '1') {
      window.$message.warning('系统自带方案不可删除')
      return
    }
    window.$dialog.error({
      title: "温馨提醒",
      content: "删除操作不可逆，是否继续？",
      positiveText: "确定",
      negativeText: "取消",
      onPositiveClick: () => {
        programmeSettingController.deleteProgrammeSetting(programme.id).then((res) => {
          if (res.code === 200) {
            window.$message.success(res.msg)
            getList()
          }
        })
      }
    })
  } else if (key == 'upload') {
    if (!client) {
      uploadToTuChuang(programme.id)
    } else {
      window.$message.warning('您没有上传权限!!')
    }
  }
}

const syncOnlineProgrammeSetting = () => {
  programmeSettingController.syncOnlineProgrammeSetting().then((res) => {
    if (res.code === 200) {
      syncTaskId.value = res.data
      syncModalShow.value = true;
    }
  })
}
</script>
